//SpringMVC-Interceptor拦截Session登录 - CSDN博客 http://blog.csdn.net/u013147600/article/details/47725699
package com.borun.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.borun.entity.UserBean;

public class LoginInterceptor implements HandlerInterceptor {

	// protected Logger log = Logger.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object obj) throws Exception {

		// 创建session
		HttpSession session = request.getSession();

		// 无需登录，允许访问的地址
		String[] allowUrls = new String[] { 
				"/Login", // 登录页面
				"/Regist",// 注册页面
				"/Logout",// 注销用户
				"api/login", // 登录请求
				"api/regist", // 注册请求
				//"api/quiz",// 测试接口
				};

		// 获取请求地址
		String url = request.getRequestURL().toString();

		// 获得session中的用户
		UserBean user = (UserBean) session.getAttribute("userToken");

		for (String strUrl : allowUrls) {
			if (url.contains(strUrl)) {
				return true;
			}
		}

		if (user == null) {
			//throw new UnLoginException("您尚未登录！");
			response.sendRedirect(request.getContextPath()+"/Account/Login");
		}
		
		// 重定向
		// response.sendRedirect(request.getContextPath()+"/toLogin");
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object obj, Exception e)
			throws Exception {
		System.out.println("afterCompletion");
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object obj, ModelAndView mv)
			throws Exception {
		System.out.println("postHandle");
	}
}
